import { LOGIN_TOKEN } from '@/global/constant'
import router from '@/router'
import { accountLoginMock, getMenuListByRoleIdMock, getUserInfoByIdMock } from '@/service/login'
import { localCache } from '@/utils/cache'
import { mapMenusToRoutes } from '@/utils/map-menus'
import type { IAccount } from '@/views/login/types'
import { defineStore } from 'pinia'
import useRoleStore from '../main/role'

interface IState {
  token: string
  userInfo: any
  userMenu: any
}
const useLoginStore = defineStore('login', {
  state: (): IState => ({
    token: localCache.getCache(LOGIN_TOKEN) ?? '',
    userInfo: localCache.getCache('userInfo') ?? {},
    userMenu: localCache.getCache('menuList') ?? []
  }),
  actions: {
    async loginAccountAction(acount: IAccount) {
      // 1. 账号登录 接口获取token信息
      const { data } = await accountLoginMock(acount)
      if (data) {
        this.token = data.token

        // 2. 将token缓存到本地
        localCache.setCache(LOGIN_TOKEN, data.token)

        // 3. 获取登录用户的详细信息
        const userInfoRes = await getUserInfoByIdMock(data.id)
        this.userInfo = userInfoRes.data
        localCache.setCache('userInfo', userInfoRes.data)

        // 4. 根据用户角色 获取用户菜单
        const menuListRes = await getMenuListByRoleIdMock(userInfoRes.data.role.id)
        this.userMenu = menuListRes.data
        localCache.setCache('menuList', menuListRes.data)

        // 获取所有角色、部门
        const roleStore = useRoleStore()
        roleStore.getAllRoles()

        // 根据菜单动态注册路由
        mapMenusToRoutes(menuListRes.data)

        // 5. 跳转首页 main
        router.push('/main')
      }
    },
    loadCacheAction() {
      const token = localCache.getCache(LOGIN_TOKEN) ?? ''
      const userInfo = localCache.getCache('userInfo') ?? {}
      const userMenu = localCache.getCache('menuList') ?? []
      this.token = token
      this.userInfo = userInfo
      this.userMenu = userMenu

      // 获取所有角色、部门
      const roleStore = useRoleStore()
      roleStore.getAllRoles()

      if (token && userInfo && userMenu) {
        mapMenusToRoutes(userMenu)
      }
    }
  }
})

export default useLoginStore
